import {createWebHistory, createRouter} from 'vue-router'
import {config} from "../config/index.js";
import userRouter from './user.js'

const Login = () => import('../views/Login.vue')
const Index = () => import('../views/Index.vue')
const Home = () => import('../views/Home.vue')

//定义组件与路径映射关系
const routes = [
    {path: '/login', component: Login, name: 'login'},
    {
        path: '/',
        component: Index,
        name: 'index',
        redirect: '/home',
        children: [
            {
                path: 'home',
                component: Home,
                name: 'home'
            }
        ]
    },
    userRouter
]

//创建router实例，并制定历史记录模式
const router = createRouter({
    history: createWebHistory(),
    routes,
})

//路由的全局守卫
router.beforeEach((to, from, next) => {
    let token = localStorage.getItem(config.tokenName);
    //增加访问组件判断，如果是访问login必须在非登录情况，访问其他组件必须在登录成功情况下
    if (to.path.indexOf('/login') !== -1) {
        if (token) {
            next('/')
        } else {
            next()
        }
    } else {
        if (token) {
            next()
        } else {
            next('/login')
        }
    }
})
//导出实例
export default router